package com.rainbow.security

import org.springframework.security.access.AccessDecisionManager
import org.springframework.security.access.AccessDeniedException
import org.springframework.security.access.ConfigAttribute
import org.springframework.security.authentication.AnonymousAuthenticationToken
import org.springframework.security.authentication.BadCredentialsException
import org.springframework.security.core.Authentication
import org.springframework.stereotype.Component

@Component
class UrlAccessDecisionManager : AccessDecisionManager {

    override fun decide(p0: Authentication, p1: Any?, p2: MutableCollection<ConfigAttribute>) {
        val iterator: Iterator<ConfigAttribute> = p2.iterator()

        while (iterator.hasNext()) {
            val ca = iterator.next()

            //当前请求需要的权限

            val needRole = ca.attribute

            if ("ROLE_LOGIN" == needRole) {
                if (p0 is AnonymousAuthenticationToken) {
                    throw BadCredentialsException("未登录")
                } else {
                    return
                }
            }
            // 当前用户所具有的权限
            val authorities = p0.authorities
            for (authority in authorities) {
                if (authority.authority == needRole) {
                    return
                }
            }
        }
        throw AccessDeniedException("权限不足！")
    }

    override fun supports(p0: ConfigAttribute?): Boolean {
        return true
    }

    override fun supports(p0: Class<*>?): Boolean {
        return true
    }
}